#!/bin/bash
set -e

# 全局变量

export REDIS_SOURCE_DIR=/root/redis-5.0.5
export BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

export MASTER1_PORT=7001
export MASTER2_PORT=7002
export MASTER3_PORT=7003
export SLAVE1_PORT=8001
export SLAVE2_PORT=8002
export SLAVE3_PORT=8003


# 创建6个redis节点目录
cd $BASE_DIR
mkdir master1 master2 master3 slave1 slave2 slave3

# 安装6个redis节点
cd $REDIS_SOURCE_DIR
make install PREFIX=$BASE_DIR/master1
make install PREFIX=$BASE_DIR/master2
make install PREFIX=$BASE_DIR/master3
make install PREFIX=$BASE_DIR/slave1
make install PREFIX=$BASE_DIR/slave2
make install PREFIX=$BASE_DIR/slave3


# 拷贝配置文件到6个节点
cd $REDIS_SOURCE_DIR
cp redis.conf $BASE_DIR/master1
cp redis.conf $BASE_DIR/master2
cp redis.conf $BASE_DIR/master3
cp redis.conf $BASE_DIR/slave1
cp redis.conf $BASE_DIR/slave2
cp redis.conf $BASE_DIR/slave3


## 修改三台主节点的配置
for i in 1 2 3
do
    PORT_NAME=MASTER${i}_PORT
    PORT=${!PORT_NAME}

    echo $PORT
    cd $BASE_DIR/master${i}

    sed -i "s/^port 6379/port ${PORT}/" redis.conf            #  修改相应端口
    sed -i 's/^protected-mode yes/protected-mode no/' redis.conf    # 实现集群时需要关闭保护模式
    sed -i 's/^daemonize no/daemonize yes/' redis.conf          # daemon模式启动
    sed -i 's/^bind 127.0.0.1/# bind 127.0.0.1/' redis.conf      # 去除仅监听本机，其他网络也能访问
    sed -i 's/^# cluster-enabled yes/cluster-enabled yes/' redis.conf # 开启集群功能 

done

### 修改三台从节点的配置
for i in 1 2 3
do
    PORT_NAME=SLAVE${i}_PORT
    PORT=${!PORT_NAME}

    echo $PORT
    cd $BASE_DIR/slave${i}

    sed -i "s/^port 6379/port ${PORT}/" redis.conf            #  修改相应端口
    sed -i 's/^protected-mode yes/protected-mode no/' redis.conf    # 实现集群时需要关闭保护模式
    sed -i 's/^daemonize no/daemonize yes/' redis.conf          # daemon模式启动
    sed -i 's/^bind 127.0.0.1/# bind 127.0.0.1/' redis.conf      # 去除仅监听本机，其他网络也能访问
    sed -i 's/^# cluster-enabled yes/cluster-enabled yes/' redis.conf # 开启集群功能 

done

### 启动3台主节点和3台从节点
for i in 1 2 3
do
    cd $BASE_DIR/master${i}
    ./bin/redis-server redis.conf
done

for i in 1 2 3
do
    cd $BASE_DIR/slave${i}
    ./bin/redis-server redis.conf
done






